/* 富文本编辑器的逻辑代码 */
import { Editor as _Editor, Toolbar as _Toolbar } from '@wangeditor/editor-for-vue';/* 重命名一下，然后再导出相同的名字 */
import '@wangeditor/editor/dist/css/style.css';
import { ref, shallowRef } from 'vue';
import { api as Request, imageUrl } from '@/utils/api';

export default function useWangeditor () {
  const Editor = _Editor;
  const Toolbar = _Toolbar;
  const editorRef = shallowRef();
  const valueHtml = ref('');
  const toolbarConfig = {};
  const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {}
  };

  /* 自定义图片上传 */
  editorConfig.MENU_CONF['uploadImage'] = {
    async customUpload (file, insertFn) {
      Request.getUploadToken({ suffix: file.type.split('/')[1] }).then(
        (res) => {
          let formdata = new FormData();
          formdata.append('file', file);
          formdata.append('token', res.result.upToken);
          formdata.append('key', res.result.fileName[0]);
          Request.postUploadImgInfo(formdata)
            .then((res) => {
              insertFn(imageUrl + '/' + res.key);
            })
            .catch((res) => {
              ElMessage.error('服务器繁忙，请稍后再试');
            });
        }
      );
    }
  }

  /* 编辑器回调函数 */
  const handleCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
  };

  /**
   * 富文本的输入事件
   * @param {*} form 哪个表单
   * @param {*} attr 哪个属性
   * @param {*} editor editor实例对象
   */
  const handleEditorChange = (form, attr, editor) => {
    console.log('change:', editor.getHtml());
    form[attr] = editor.getHtml();
  };

  /* 销毁富文本组件 */
  const handleDestroyEditor = () => {
    console.log(editorRef);
    const editor = editorRef.value;
    if (editor == null) return;
    /* TODO：销毁编辑器会报错，等作者修改bug */
    // editor.destroy();
    console.log('destroy');
  }

  return {
    Editor, Toolbar, editorRef, valueHtml, toolbarConfig, editorConfig, handleCreated, handleEditorChange, handleDestroyEditor
  }
}

